<?php

namespace App\Services\admin;

use App\Models\admin\AdminUser;
use App\Services\BaseService;
use Illuminate\Support\Facades\Hash;

class AdminUserService extends BaseService
{
    /**
     * 校验登录
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public static function checkLogin($data)
    {
        try {
            $user = AdminUser::where('username', $data['username'])->first();

            return $user;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 分页数据查询
     *
     * @Desc:
     *
     * @return mixed
     *
     * @author: zhx
     *
     * @Time: 2023/8/9 15:04
     */
    public static function getPageData($requestData)
    {
        [$perPage, $page, $orderBy, $orderDir] = [
            isset($requestData['perPage']) ? $requestData['perPage'] : 20,
            isset($requestData['page']) ? $requestData['page'] : 1,
            isset($requestData['orderBy']) ? $requestData['orderBy'] : 'id',
            isset($requestData['orderDir']) ? $requestData['orderDir'] : 'desc',
        ];
        $models = AdminUser::query();
        if (isset($requestData['keywords'])) {
            $models->orWhere('name', 'like', '%'.$requestData['keywords'].'%');
            $models->orWhere('username', 'like', '%'.$requestData['keywords'].'%');
            $models->orWhere('phone', 'like', '%'.$requestData['keywords'].'%');
        }
        if (isset($requestData['state'])) {
            $models->where('state', $requestData['state']);
        }
        $models->where('super_admin', '<>', 1);
        $user = $models->whereNull('deleted_at')->orderBy($orderBy, $orderDir)->paginate($perPage);
        foreach ($user as $key => $item) {
            $roleInfo = RoleService::info($item->roles);
            $user->items()[$key]->roleName = $roleInfo ? $roleInfo->name : '未配置';
        }

        return $user;
    }

    /**
     * 数据查询
     *
     * @Desc:
     *
     * @return mixed
     *
     * @author: zhx
     *
     * @Time: 2023/8/9 15:04
     */
    public static function getData($requestData)
    {
        [$orderBy, $orderDir] = [
            isset($requestData['orderBy']) ? $requestData['orderBy'] : 'id',
            isset($requestData['orderDir']) ? $requestData['orderDir'] : 'desc',
        ];
        $models = AdminUser::query();
        if (isset($requestData['keywords'])) {
            $models->orWhere('name', 'like', '%'.$requestData['keywords'].'%');
            $models->orWhere('username', 'like', '%'.$requestData['keywords'].'%');
            $models->orWhere('phone', 'like', '%'.$requestData['keywords'].'%');
        }
        if (isset($requestData['state'])) {
            $models->where('state', $requestData['state']);
        }
        $user = $models->where('deleted_at', '<>', '')->orderBy($orderBy, $orderDir)->get()->toArray();
        foreach ($user as $key => $item) {
            $roleInfo = RoleService::info($item->roles);
            $user->items()[$key]->roleName = $roleInfo ? $roleInfo->name : '未配置';
        }

        return $user;
    }

    /**
     * 编辑
     *
     * @Desc:
     *
     * @return \Illuminate\Http\JsonResponse
     *
     * @throws \Illuminate\Validation\ValidationException
     *
     * @author: zhx
     *
     * @Time: 2023/8/10 14:44
     */
    // 在这里进行表单验证和用户更新逻辑
    public static function edit($id, $requestData)
    {
        $models = AdminUser::query();
        $models->where('id', $id);

        return $models->update($requestData);
    }

    /**
     * 添加
     *
     * @Notes:
     *
     * @Author: zhx
     *
     * @Date: 2023-07-01
     *
     * @Time: 14:02
     *
     * @Interface create
     */
    public static function create($requestData)
    {
        $requestData['password'] = Hash::make($requestData['password']);
        $result = AdminUser::create($requestData);

        return $result;
    }

    /**
     * 详细
     *
     * @Notes:
     *
     * @Author: zhx
     *
     * @Date: 2023-07-01
     *
     * @Time: 14:02
     *
     * @Interface info
     */
    public static function info($id)
    {
        $models = AdminUser::query();

        return $models->with(['hasRole'])->where('id', $id)->first();
    }

    /**
     * 获取超级管理员详细
     *
     * @Notes:
     *
     * @Author: zhx
     *
     * @Date: 2023-07-01
     *
     * @Time: 14:02
     *
     * @Interface info
     */
    public static function infoBySuper()
    {
        $models = AdminUser::query();
        $info = $models->where('is_super', 1)->first();

        return $info->id;
    }

    /**
     * 删除
     *
     * @Notes:
     *
     * @Author: zhx
     *
     * @Date: 2023-07-01
     *
     * @Time: 14:02
     *
     * @Interface info
     */
    public static function destroy($id)
    {
        $models = AdminUser::query();

        return $models->where('id', $id)->update([
            'deleted_at' => date('Y-m-d H:i:s'),
        ]);
    }

    /**
     * 重置密码
     *
     * @return \Illuminate\Http\JsonResponse
     * User: zhx
     * Date: 2023/6/30 14:30
     */
    public static function resetPassword($id)
    {
        $models = AdminUser::query();
        $password = Check::getRandStr(8);
        $ret = $models->where('id', $id)->update([
            'password' => password_hash($password, PASSWORD_BCRYPT),
            'reset_password' => $password,
        ]);

        return $ret;
    }

    /**
     * 状态更新
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public static function statusEdit($id)
    {
        $models = AdminUser::query();
        $info = $models->where('id', $id)->first();
        if ($info->state == 1) {
            $ret = $models->where('id', $id)->update([
                'state' => 0,
            ]);
        } else {
            $ret = $models->where('id', $id)->update([
                'state' => 1,
            ]);
        }

        return $ret;
    }

    /**
     * 设置密码
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public static function setPassword($uid, $requestData)
    {

        $ret = AdminUser::where('id', $uid)->update([
            'password' => password_hash($requestData['new_password'], PASSWORD_BCRYPT),
        ]);

        return $ret;
    }

    /**
     * 记录登录日志
     *
     * @return void
     */
    public static function addLoginlog($userId, $username, $userAgent, $ip, $type)
    {
        $result = \App\Models\common\LoginLogs::create([
            'user_id' => $userId,
            'username' => $username,
            'user_agent' => $userAgent,
            'ip_address' => $ip,
            'state' => $type,
        ]);

        return $result;
    }
}
